package com.bobo.controller;

import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import com.bobo.auth.common.Result;
import com.bobo.domain.SysCity;
import com.bobo.domain.SysUser;
import com.bobo.service.SysCityService;
import com.bobo.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("auth")
public class CityController {

    @Autowired
    SysCityService sysCityService;
    @Autowired
    RedisTemplate redisTemplate;
    @RequestMapping("/city/list")
     public Result list(){
        //使用redis缓存
        List<SysCity> nodeList=null;
        if(redisTemplate.hasKey("cityList")){
            nodeList= (List<SysCity>) redisTemplate.opsForValue().get("cityList");
        }else {
            nodeList = sysCityService.list();//从数据库获取
            redisTemplate.opsForValue().set("cityList",nodeList);//存入redis
        }

        TreeNodeConfig treeNodeConfig = new TreeNodeConfig();
        List<Tree<String>> treeNodes = TreeUtil.build(nodeList, "1", treeNodeConfig,
                (treeNode, tree) -> {
                    tree.setId(treeNode.getId()+"");
                    tree.setParentId(treeNode.getPid()+"");
                    tree.setName(treeNode.getName());
                });
        return Result.success(treeNodes);
    }
}
